// app/controller/comment.js
'use strict';

const Controller = require('egg').Controller;

class CommentController extends Controller {
    // 创建评论
    async create() {
        const { ctx, service } = this;

        try {
            // 参数验证
            const rules = {
                post_id: { type: 'integer', required: true },
                content: { type: 'string', required: true },
                parent_id: { type: 'integer', required: false }
            };
            ctx.validate(rules);

            const commentData = ctx.request.body;

            // 从token中获取用户ID
            const token = ctx.request.header.token;
            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);

            const result = await service.comment.create({
                ...commentData,
                user_id: decode.user_id
            });

            ctx.body = {
                code: 0,
                data: result,
                msg: '评论成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '评论失败'
            };
        }
    }

    // 获取帖子评论列表
    async list() {
        const { ctx, service } = this;

        try {
            const { post_id } = ctx.params;
            const query = ctx.query;

            // 验证帖子ID参数
            const rules = {
                post_id: { type: 'id', required: true }
            };
            ctx.validate(rules, ctx.params);

            const result = await service.comment.getPostComments(post_id, query);

            ctx.body = {
                code: 0,
                data: result,
                msg: '获取成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取评论列表失败'
            };
        }
    }

    // 获取评论回复列表
    async replies() {
        const { ctx, service } = this;

        try {
            const { comment_id } = ctx.params;
            const query = ctx.query;

            // 验证评论ID参数
            const rules = {
                comment_id: { type: 'id', required: true }
            };
            ctx.validate(rules, ctx.params);

            const result = await service.comment.getCommentReplies(comment_id, query);

            ctx.body = {
                code: 0,
                data: result,
                msg: '获取成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取回复列表失败'
            };
        }
    }

    // 获取评论详情
    async detail() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;

            // 验证ID参数
            const rules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(rules, ctx.params);

            const comment = await service.comment.getCommentWithUser(id);

            ctx.body = {
                code: 0,
                data: comment,
                msg: '获取成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取评论详情失败'
            };
        }
    }

    // 更新评论
    async update() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;
            const updateData = ctx.request.body;

            // 验证路径参数
            const paramRules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(paramRules, ctx.params);

            // 验证body参数
            const bodyRules = {
                content: { type: 'string', required: true }
            };
            ctx.validate(bodyRules);

            // 从token中获取用户ID，验证权限
            const token = ctx.request.header.token;
            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);

            // 检查评论是否存在且属于当前用户
            const comment = await ctx.model.Comment.findByPk(id);
            if (!comment) {
                throw new Error('评论不存在');
            }
            if (comment.user_id !== decode.user_id) {
                throw new Error('无权修改此评论');
            }

            const result = await service.comment.updateComment(id, updateData);

            ctx.body = {
                code: 0,
                data: result,
                msg: '更新成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '更新评论失败'
            };
        }
    }
    // 删除评论
    async delete() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;

            // 验证ID参数
            const rules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(rules, ctx.params);

            // 优先使用 adminToken，如果没有则使用普通 token
            let token = ctx.request.header.admintoken || ctx.request.header.token;

            if (!token) {
                throw new Error('未提供认证令牌');
            }

            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);

            // 检查评论是否存在
            const comment = await ctx.model.Comment.findByPk(id);
            if (!comment) {
                throw new Error('评论不存在');
            }

            // 权限验证：管理员可以删除任何评论，普通用户只能删除自己的评论
            const isAdmin = decode.type === 'admin' || ctx.request.header.admintoken;
            if (!isAdmin && comment.user_id !== decode.user_id) {
                throw new Error('无权删除此评论');
            }

            await service.comment.deleteComment(id);

            ctx.body = {
                code: 0,
                data: null,
                msg: '删除成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '删除评论失败'
            };
        }
    }

    // 获取用户的评论列表
    async userComments() {
        const { ctx, service } = this;

        try {
            const { user_id } = ctx.params;
            const query = ctx.query;

            // 验证用户ID参数
            const rules = {
                user_id: { type: 'id', required: true }
            };
            ctx.validate(rules, ctx.params);

            const result = await service.comment.getUserComments(user_id, query);

            ctx.body = {
                code: 0,
                data: result,
                msg: '获取成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取用户评论失败'
            };
        }
    }
}

module.exports = CommentController;